#include "stdafx.h"
#include "AsyncTask.h"     

const int MAX_JOIN_TIME = 100; // ms

CAsyncTask::CAsyncTask(int threadPoolSize) : m_threadPoolSize(threadPoolSize)
{
}

CAsyncTask::~CAsyncTask(){
}

bool CAsyncTask::Start() 
{
    m_ioService.reset(new boost::asio::io_service());
    m_idleWork.reset(new boost::asio::io_service::work(*m_ioService.get()));

    for(int i = 0; i < m_threadPoolSize; i++) {
        boost::shared_ptr<boost::thread> thread(new boost::thread(boost::bind(&boost::asio::io_service::run, m_ioService)));
        m_workThreadPool.push_back(thread);
    }
    
    return true;
}

void CAsyncTask::Stop() 
{
    try {
        m_ioService->stop();
        m_idleWork.reset();
    }
    catch(...) {
    }

    std::vector<boost::shared_ptr<boost::thread> > ::iterator iter = m_workThreadPool.begin();
    while(iter != m_workThreadPool.end()) {
        boost::thread::id pid = (*iter)->get_id();
        (*iter)->interrupt();
        (*iter)->join();

        iter = m_workThreadPool.erase(iter);
    }

    return;
}
